<?php


namespace app\astrologer\controller\v1;


use app\aliyun\controller\AliyunFilterWord;
use app\astrologer\controller\AstrAuth;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\zlcr2\Zlcr2AstrTasks;
use app\common\cachemodel\zlcr2\Zlcr2QuestionUserView;
use app\common\cachemodel\zlcr2\Zlcr2UserAddQuestion;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestionComment;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrMessage;
use app\common\cachemodel\ZlcrTag;
use app\common\lib\Push;
use app\common\lib\Util;
use app\common\model\MessageCenter;
use app\common\model\Recode;
use app\common\model\User;
use think\Cache;
use think\Db;
use think\Env;
use think\Log;
use think\response\Json;

class Question extends AstrAuth
{
    /**
     * 获取接单列表
     */
    public function questionWaitingList()
    {
        $questionModel = new Zlcr2UserQuestion();
        $astrModel = new ZlcrAstr();
        $astrTaskModel = new Zlcr2AstrTasks();
        // 完善资料 状态
        $isCompleteInformation = isset($this->astrInfo['extend']['is_complete_information']) ? 1 : 0;
        $nowTime = $this->request->time();
        if (!(in_array($this->headers['app-type'], ['ios', 'android'], true) && !$isCompleteInformation))
        {   // $waitingListIds = $questionModel->getQuestionWaitingListIds(1);
            $astrAnswerGids = $astrTaskModel->getAstrAnswerGids($this->astrInfo);
            // 获取弃答 问题id
            $discardQids = $astrTaskModel->getDiscardQids($this->astrInfo['id']);
            // 从数据库获取待接单任务
            $waitingListIds = $questionModel->where(['status' => ['in', [2, 4]], 'astr_id' => 0, 'gid' => ['in', $astrAnswerGids], 'id' => ['not in', $discardQids]])->order('consult_time asc')->limit(10)->column('id');

            $questionInfos = $questionModel->batchGetInfoByIds($waitingListIds, ['status', 'is_anonymity', 'uid', 'gid', 'activity_discount', 'question_type', 'consult_time', 'question', 'question_des', 'id', 'astr_id']);

            $questionAnswerConfig = (new AppConfig())->configInfo('question_answer');
            $showDelayTime = (int)($questionAnswerConfig['show_delay_time'] ?? 0);
            foreach ($questionInfos as $qidItem => $value)
            {
                if (!$this->isConsultAstro && $nowTime - $value['consult_time'] <= $showDelayTime)
                {   // 不是 准有好事 咨询师
                    unset($questionInfos[$qidItem]);
                }
            }
        } else
        {
            $questionInfos = [];
        }
        $resData = [];
        $userInfoList = [];
        $goodPrice = [];    // 没有打折情况下分成
        $goodInfo = Util::getZhunleQuestionAnswerConfig();
        foreach ($questionInfos as $qid => $questionInfoItem)
        {
            if ($questionInfoItem['status'] === 2 || ($questionInfoItem['status'] === 4 && $questionInfoItem['astr_id'] === 0))
            {
                $userDes = '小行星神秘人';
                $nickname = '匿名用户';
                $avatar = '/test/question_answer/anonymity1.png';
                if ($questionInfoItem['is_anonymity'] !== 1)
                {
                    if (isset($userInfoList[$questionInfoItem['uid']]))
                    {
                        $userDes = $userInfoList[$questionInfoItem['uid']]['user_des'];
                        $nickname = $userInfoList[$questionInfoItem['uid']]['nickname'];
                        $avatar = $userInfoList[$questionInfoItem['uid']]['avatar'];
                    } else
                    {
                        $userInfo = (new User())->getUserinfo(['id' => $questionInfoItem['uid']]);
                        if ($userInfo['rid'])
                        {
                            $recode = (new Recode())->getRecode(['id' => $userInfo['rid']]);
                            if ($recode)
                            {
                                $utilModel = new Util();
                                $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                            }
                        }
                        $nickname = $userInfo['nickname'];
                        $avatar = $userInfo['avatar'];
                        $userInfoList[$questionInfoItem['uid']] = [
                            'nickname' => $nickname,
                            'avatar' => $avatar,
                            'user_des' => $userDes
                        ];
                    }
                }

                if (isset($goodPrice[$questionInfoItem['gid']]))
                {
                    $price = (float)(sprintf("%.2f", $goodPrice[$questionInfoItem['gid']] * $questionInfoItem['activity_discount']));
                } else
                {
                    // 获取咨询师等级
                    $level = $this->astrInfo[$astrModel->astrTypeLevelKeyName[$questionInfoItem['question_type']]['level']] ?? 0;
                    $level = $level > 0 ? $level : 1;
                    // 计算未参与活动分成金额
                    $oldPrice = (float)(sprintf('%.2f', $goodInfo[$questionInfoItem['gid']]['price'] * ($astrModel->getAstrQuestionAnswerProportion($this->request->time(), $questionInfoItem['question_type'], $level))));
                    // 计算参与活动后分成金额
                    $price = (float)(sprintf("%.2f", $oldPrice * $questionInfoItem['activity_discount']));
                    // 记录未参与活动分成金额
                    $goodPrice[$questionInfoItem['gid']] = $oldPrice;
                }
                $price = Util::getAfterTaxAmount($price); // 扣除手续费及营业税费
                $resData[] = [
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'create_time' => Util::timeToStr($questionInfoItem['consult_time']),
                    'user_des' => $userDes,
                    'qid' => $questionInfoItem['id'],
                    'type' => $questionInfoItem['question_type'],
                    'question' => $questionInfoItem['question'],
                    'question_des' => $questionInfoItem['question_des'],
                    'price' => $price,
                ];
            } else
            {   // 非待接单状态 删除接单列表
                $questionModel->questionWaitingListDel($questionInfoItem['id']);
            }
        }

        $msg = '请求成功';
        if (count($resData) === 0)
        {
            if (in_array($this->headers['app-type'], ['ios', 'android'], true) && !$isCompleteInformation)
            {
                $msg = '请完善信息后，再来接单！';
            } else
            {
                $msg = '接单数据为空，您可以点击刷新按钮进行刷新！';
            }
        }
        return show(config('code.success'), $msg, [
            'underway_des' => $astrTaskModel->getUnderwayDes($this->astrInfo['id']),
            'list' => $resData
        ]);
    }

    /**
     * 问答 咨询师接单
     */
    public function astrReceiving()
    {
        $qid = input('qid/s', '');
        $questionModel = new Zlcr2UserQuestion();
        $astrModel = new ZlcrAstr();
        if (empty($qid))
        {
            return show(config('code.error'), '请求异常，请稍后再试');
        }
        if ((int)$this->astrInfo['check_status'] !== 40)
        {
            return show(config('code.error'), '账号状态异常，接单失败');
        }

        $questionInfo = $questionModel->getInfoById($qid, []);
        if (!$questionInfo)
        {
            return show(config('code.error'), '抢单失败，该条任务列表消失');
        }

        if (Cache::get('question_answer:is_underway:' . $this->astrInfo['id'], false))
        {
            return show(config('code.error'), '抢单失败，还有待解答的任务');
        }
        // 判断占星师是否接单功能冻结
        if ($this->astrInfo['answer_pause_time'] > $this->request->time())
        {
            return show(config('code.error'), '因你3天内超10次弃答，问答接单资格冻结3天，' . date('m月d日H:i', $this->astrInfo['answer_pause_time']) . '自动解封。');
        }
        // 判断占星师 是否具备接单资格
        $level = $this->astrInfo[$astrModel->astrTypeLevelKeyName[$questionInfo['question_type']]['level']] ?? 0;

        if ($level === 0)
        {
            return show(config('code.error'), '暂不支持解答相关问题，快去考试认证吧～');
        }

        if ($level < 0)
        {
            return show(config('code.error'), '因你的不当行为，问答-占星接单资格已冻结，如有疑问请联系微信：zhunleapp2');
        }

        if ($this->astrInfo[$astrModel->astrTypeLevelKeyName[$questionInfo['question_type']]['score']] < 80)
        {
            return show(config('code.error'), '抢单失败，账号该类型问答接单功能冻结');
        }

        $goodInfo = config('zlcr2_question.info');
        if ($level < $goodInfo[$questionInfo['gid']]['level'])
        {
            return show(config('code.error'), '抢单失败，没有接单资质');
        }

        if (($questionInfo['status'] !== 2) && !($questionInfo['status'] === 4 && $questionInfo['astr_id'] === 0))
        {
            return show(config('code.error'), '抢单失败，请刷新后重试');
        }

        $receivingRes = $questionModel->astrReceivingLock($qid);

        if ($receivingRes)
        {   // 抢单成功
            $questionModel->UpdateData($qid, [
                'status' => 4,// 待解答
                'astr_id' => $this->astrInfo['id'],
                'astr_receiving_time' => $this->request->time(),
            ]);
            // 添加占星师任务表
            $id = (new Zlcr2AstrTasks())->SaveData($this->astrInfo['id'], [
                'astr_id' => $this->astrInfo['id'],
                'qa_level' => $level,
                'qid' => $qid,
                'question_type' => $questionInfo['question_type'],
                'status' => 1,
                'create_time' => $this->request->time(),
            ]);

            // 1、发送占星师回复超时检测队列 1小时内必须回答
            Util::queuePush('question_answer_question_astr_reply_check', ['task_id' => $id], 3600);
            // 2、发送占星师 40分钟内未回复 对占星师进行通知队列
            Util::queuePush('question_answer_astr_reply_notify', ['task_id' => $id], 2400);

            return show(config('code.success'), '抢单成功', ['task_id' => (int)$id]);
        } else
        {   // 抢单失败
            return show(config('code.error'), '抢单失败，请刷新后重试');
        }
    }

    /**
     * 咨询师 进行中列表
     */
    public function astrTaskList()
    {
        $type = input('type/d', 1);
        $astrModel = new ZlcrAstr();
        $questionModel = new Zlcr2UserQuestion();
        $astrTaskModel = new Zlcr2AstrTasks();
        $addQuestionModel = new Zlcr2UserAddQuestion();
        if ($type === 1)
        {
            $this->request->get(['page' => -1]);
            $taskLists = $astrTaskModel->getListPage($this->astrInfo['id'], 'create_time', ['id', 'qid', 'earning', 'qa_level', 'create_time'], 1);
        } else
        {
            $this->request->get(['page' => 1]);
            $this->request->get(['limit' => 20]);
            $taskLists = $astrTaskModel->getListPage($this->astrInfo['id'], 'update_time', ['id', 'qid', 'earning', 'qa_level', 'create_time'], 2);
        }

        $qids = $taskLists['data'] ? array_column($taskLists['data'], 'qid') : [];
        $taskIdInfo = $taskLists['data'] ? array_column($taskLists['data'], null, 'qid') : [];

        $questionList = $questionModel->batchGetInfoByIds($qids);

        $resData = [];
        $userInfoList = [];
        foreach ($questionList as $qid => $questionItem)
        {
            $userDes = '小行星神秘人';
            $nickname = '匿名用户';
            $avatar = '/test/question_answer/anonymity1.png';
            if ($questionItem['is_anonymity'] !== 1)
            {
                if (isset($userInfoList[$questionItem['uid']]))
                {
                    $userDes = $userInfoList[$questionItem['uid']]['user_des'];
                    $nickname = $userInfoList[$questionItem['uid']]['nickname'];
                    $avatar = $userInfoList[$questionItem['uid']]['avatar'];
                } else
                {
                    $userInfo = (new User())->getUserinfo(['id' => $questionItem['uid']]);
                    if ($userInfo['rid'])
                    {
                        $recode = (new Recode())->getRecode(['id' => $userInfo['rid']]);
                        if ($recode)
                        {
                            $utilModel = new Util();
                            $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                        }
                    }
                    $nickname = $userInfo['nickname'];
                    $avatar = $userInfo['avatar'];
                    $userInfoList[$questionItem['uid']] = [
                        'nickname' => $nickname,
                        'avatar' => $avatar,
                        'user_des' => $userDes
                    ];
                }
            }

            switch ($questionItem['status'])
            {
                case 4:
                    $endTime = $questionItem['astr_receiving_time'] + 3600 - $this->request->time();
                    $endTime = $endTime > 0 ? $endTime : 0;
                    $tip1 = $endTime;
                    $tip2 = '内完成作答';
                    break;
                case 5:
                    $tip1 = '';
                    $tip2 = '等待用户追问';
                    break;
                case 6:
                case 7:
                    if (empty($questionItem['lock_reason']))
                    {
                        $tip1 = '本单收益：';
                        $tip2 = ((float)$taskIdInfo[$qid]['earning']) . '元';
                    } else
                    {
                        $tip1 = '';
                        $tip2 = '扣除收益';
                    }
                    break;
                case 8:
                    $addQuestionList = $addQuestionModel->getQuestionAddQuestionInfo($qid);
                    $addQuestionInfo = array_pop($addQuestionList);
                    if (!$addQuestionInfo)
                    {
                        break;
                    }
                    $endTime = Util::getToAnswerTime($addQuestionInfo['pay_time']);
                    if ($endTime < 0)
                    {   // 超时
                        $tip1 = '';
                        $tip2 = '已超时';
                    } else
                    {   // 未超时
                        $tip1 = $endTime;
                        $tip2 = '内回复追问';
                    }
                    break;
                default:
                    $tip1 = '';
                    $tip2 = '';
            }

            $proportion = ($astrModel->getAstrQuestionAnswerProportion($taskIdInfo[$qid]['create_time'], $questionItem['question_type'], $taskIdInfo[$qid]['qa_level']) * 100) . '%';
            $successTime = $questionItem['success_time'] ? date('Y-m-d H:i:s', $questionItem['success_time']) : '';
            $addQuestionNum = $addQuestionModel->getQuestionAddQuestionNum($qid, 0);

            $resData[] = [
                'qid' => $qid,
                'proportion' => $proportion,
                'success_time' => $successTime,
                'add_question_num' => $addQuestionNum,
                'nickname' => $nickname,
                'avatar' => $avatar,
                'create_time' => Util::timeToStr($questionItem['consult_time']),
                'user_des' => $userDes,
                'task_id' => (int)$taskIdInfo[$qid]['id'],
                'type' => $questionItem['question_type'],
                'question' => $questionItem['question'],
                'question_des' => $questionItem['question_des'],
                'des1' => $tip1,
                'des2' => $tip2,
                'status' => $questionItem['status'],
                'earning' => $type === 1 ? $questionModel->getQuestionEarning2($questionItem, $taskIdInfo[$qid]) : (float)$taskIdInfo[$qid]['earning'],// 回答收益 包含追问的预计收益
                'astr_receiving_time' => date('Y-m-d H:i:s', $questionItem['astr_receiving_time']), // 接单时间
            ];
        }

        $msg = '请求成功';
        if (count($resData) === 0)
        {//1=>进行中 2=>已完成
            if (1 === $type)
            {
                $msg = '进行中的数据为空！';
            } else
            {
                $msg = '已完成的数据为空！';
            }

        }
        return show(config('code.success'), $msg, [
            'underway_des' => $astrTaskModel->getUnderwayDes($this->astrInfo['id']),
            'list' => $resData
        ]);
    }

    /**
     * 弃答-问题
     */
    public function discardQuestion()
    {
        $taskId = input('task_id/d', '');

        $questionModel = new Zlcr2UserQuestion();
        $astrTaskModel = new Zlcr2AstrTasks();

        $taskInfo = $astrTaskModel->getInfoById($taskId);

        $questionInfo = $questionModel->getInfoById($taskInfo['qid'], []);
        if (!$questionModel || $questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }
        if ($questionInfo['status'] !== 4)
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }
        if ($questionInfo['astr_receiving_time'] + 300 < $this->request->time())
        {
            return show(config('code.error'), '接单已超过5分钟，不可弃答。');
        }
        // 获取已弃答次数
        $discardNum = $astrTaskModel->getAstrDiscardQuestionNumByToday($this->astrInfo['id']);

        if ($questionInfo['discard_num'] >= 3)
        {
            // 取消订单退款
            $OrderModel = new \app\common\cachemodel\Orders();
            $orders = $OrderModel->getInfoById($questionInfo['order_num']);
            $res = $OrderModel->refund($questionInfo['uid'], $orders, $orders['total_amount']);
            if ($res['status'])
            {
                // 问题弃答
                $questionModel->UpdateData($taskInfo['qid'], [
                    'status' => 9,  // 弃答三次退款
                    'astr_id' => 0,
                    'astr_receiving_time' => 0,
                    'discard_num' => $questionInfo['discard_num'] + 1,
                ]);
                // 向用户发送消息
                $msgContent = "你开启的悬赏问答，订单编号：{$questionInfo['order_num']}因问题无法回答自动取消，资金将原路返还，请注意查收。请检查问题重新下单。";
                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $questionInfo['uid'],
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 4,//
                    'title' => '订单取消通知',
                    'content' => $msgContent,// 消息中心跳转地址
                    'link' => "order_details?order_id={$questionInfo['order_num']}&order_type=22&need_auth=0",  // 订单详情
                    'target' => 'local',
                    'create_time' => $this->request->time()
                ];
                (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
                $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "order_details?order_id={$questionInfo['order_num']}&order_type=22&need_auth=0"];
                // PUSH推送报告首页
                (new Push())->pushUserMsg($questionInfo['uid'], $msgContent, $pushData);
                // 发送短信
                $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
                if ($userInfo && $userInfo['tel'])
                {
                    Util::sendHySms([$userInfo['tel']], '', 52340, ['order_num' => $questionInfo['order_num']]);
                }
            } else
            {
                // 问题弃答 退款失败  弃答
                $questionModel->UpdateData($taskInfo['qid'], [
                    'astr_id' => 0,
                    'astr_receiving_time' => 0,
                    'discard_num' => $questionInfo['discard_num'] + 1,
                ]);
            }

        } else
        {
            // 问题弃答
            $questionModel->UpdateData($taskInfo['qid'], [
                'astr_id' => 0,
                'astr_receiving_time' => 0,
                'discard_num' => $questionInfo['discard_num'] + 1,
            ]);
        }

        $taskUpdate = [
            'status' => 3,
            'update_time' => $this->request->time(),
        ];

        if ($discardNum >= 10)
        {
            $taskUpdate['is_lock_receiving'] = 1; // 当前任务是否导致账号接单资格冻结 1=>冻结 0=>不冻结
        }
        // 更新占星师任务状态信息
        $astrTaskModel->UpdateData($taskId, $this->astrInfo['id'], $taskUpdate);

        if ($discardNum >= 10)
        {
            // 冻结 问答接单资格    3天
            (new ZlcrAstr())->UpdateData($this->astrInfo['id'], ['id' => $this->astrInfo['id']], ['answer_pause_time' => $this->request->time() + 259200]);
            // 给占星师发冻结消息
            // 占星师站内信
            (new ZlcrAstrMessage())->add($questionInfo['astr_id'], [
                'status' => 0,
                'is_read' => 0,
                'astr_id' => $questionInfo['astr_id'],
                'type' => 9, // 默认消息
                'title' => '问答接单封禁通知',
                'content' => '账号封禁通知，因你3天内超10次弃答问答问题，问答接单资格冻结3天处理，3天后自动解封，如有疑问请微信联系。',
                'target' => 'local',
                'link' => 'empty',
                'create_time' => $this->request->time()
            ]);
        }

        return show(config('code.success'), '弃答成功');
    }

    /**
     * 问题详情
     */
    public function questionInfo()
    {
        $taskId = input('task_id/d', '');

        $astrTaskModel = new Zlcr2AstrTasks();
        $astrModel = new ZlcrAstr();

        $is_manage = false;//是否是 后台查看的问题内容
        $app_type = $this->headers['app-type'];
        if (strpos($app_type, 'manage') !== false && (int)$taskId > 999999999)
        {
            $is_manage = true;
        }

        if ($is_manage)
        {
            $qid = $taskId;
            $taskInfo = null;
        } else
        {
            $taskInfo = $astrTaskModel->getInfoById($taskId);
            if (!$taskInfo || $taskInfo['astr_id'] !== $this->astrInfo['id'])
            {
                if (strpos($app_type, 'manage') === false)
                {//不是后台查看的占星师内容
                    return show(config('code.error'), '服务异常，问题不存在');
                }
            }
            $qid = $taskInfo['qid'];
        }

        $questionModel = new Zlcr2UserQuestion();
        $questionInfo = $questionModel->getInfoById($qid, ['astr_id', 'uid', 'question_type', 'question_extend', 'status', 'astr_receiving_time', 'question', 'question_des', 'consult_time', 'is_anonymity', 'answer_content', 'answer_duration', 'reply_time', 'question_imgs', 'gid', 'activity_discount']);

        if (!$questionModel)
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }

        $userDes = '小行星神秘人';
        if ($questionInfo['is_anonymity'] !== 1)
        {
            $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
            if ($userInfo['rid'])
            {
                $recode = (new Recode())->getRecode(['id' => $userInfo['rid']]);
                if ($recode)
                {
                    $utilModel = new Util();
                    $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                }
            }
        }

        $userNickname = $userInfo['nickname'] ?? '匿名用户';
        $userAvatar = $userInfo['avatar'] ?? '/test/question_answer/anonymity1.png';

        $questionData = null;
        switch ($questionInfo['question_type'])
        {
            case 1:
                if (isset($questionInfo['question_extend']['recode1']) && $questionInfo['question_extend']['recode1'])
                {
                    $questionData['astro_data'][] = [
                        'nickname' => $questionInfo['question_extend']['recode1']['name'],
                        'avatar' => $questionInfo['question_extend']['recode1']['avatar'],
                        'sex' => $questionInfo['question_extend']['recode1']['type'],
                        'age' => Util::getAgeByBirth($questionInfo['question_extend']['recode1']['year'], $questionInfo['question_extend']['recode1']['month'], $questionInfo['question_extend']['recode1']['day'], 2),
                    ];
                }
                if (isset($questionInfo['question_extend']['recode2']) && $questionInfo['question_extend']['recode2'])
                {
                    $questionData['astro_data'][] = [
                        'nickname' => $questionInfo['question_extend']['recode2']['name'],
                        'avatar' => $questionInfo['question_extend']['recode2']['avatar'],
                        'sex' => $questionInfo['question_extend']['recode2']['type'],
                        'age' => Util::getAgeByBirth($questionInfo['question_extend']['recode2']['year'], $questionInfo['question_extend']['recode2']['month'], $questionInfo['question_extend']['recode2']['day'], 2),
                    ];
                }
                break;
            case 2:
            case 3:
                $questionData = $questionInfo['question_extend'];
                break;
            default:
        }

        $tipDes = [
            'tip' => '',
            'time' => 0,
            'status' => 0,
            'tip1' => '',
            'type' => 1
        ];
        $answerData = null;
        $giveUpData = null;
        $answerRule = $questionModel->answerRule($questionInfo['question_type']) ?? ['text_min' => 100, 'text_max' => 240, 'duration_min' => (Util::isOnline() ? 120 : 12), 'duration_max' => 300];
        if ($taskInfo && $taskInfo['status'] === 3)
        {
            $addQuestion = null;
            $hintDes = '已弃答';
        } elseif ($taskInfo && $taskInfo['status'] === 5)
        {
            $tipDes = [
                'tip' => '',
                'time' => 0,
                'status' => 0,
                'tip1' => '',
                'type' => 1
            ];
            $addQuestion = null;
            $hintDes = '回复超时,任务已取消';
        } else
        {
            if ($questionInfo['status'] === 4)
            {   // 问题待解答
                $endTime = $questionInfo['astr_receiving_time'] + 3600 - $this->request->time();
                $endTime = $endTime > 0 ? $endTime : 0;
                $goodInfo = Util::getZhunleQuestionAnswerConfig();
                $oldPrice = (float)(sprintf('%.2f', $goodInfo[$questionInfo['gid']]['price'] * $astrModel->getAstrQuestionAnswerProportion($taskInfo['create_time'], $questionInfo['question_type'], $taskInfo['qa_level'])));
                $price = (float)(sprintf("%.2f", $oldPrice * $questionInfo['activity_discount']));
                // 扣除手续费及营业税费
                $price = Util::getAfterTaxAmount($price);
                $hintBottomBuyBar = '完成作答且通过抽查可得' . $price . '元';
                // 接单5分钟内
                if ($questionInfo['astr_receiving_time'] + 300 > $this->request->time())
                {
                    // 获取已弃答次数
                    $discardNum = $astrTaskModel->getAstrDiscardQuestionNumByToday($this->astrInfo['id']);
                    $giveUpData = [
                        'all_num' => 3,
                        'left_num' => $discardNum,
                        'hint' => '3天内弃答超10次冻结接单资格3天，',
                        'toast' => '如果3天内，弃答超10次，所有问答接单资格将被冻结3日，当前已弃答' . $discardNum . '次。',
                    ];
                }

                $tipDes = [
                    'tip' => '规定回答时间还剩：',
                    'time' => $endTime,
                    'status' => 1,
                    'tip1' => '问题回复超时，已取消',
                    'type' => 1
                ];
            } elseif ($questionInfo['status'] === 8)
            {   // 追问待解答
                $hintBottomBuyBar = '回复追问';
                $answerRule = [
                    'text_min' => 30,
                    'text_max' => 150,
                    'duration_min' => 20,
                    'duration_max' => 300,
                ];
            } elseif ($questionInfo['status'] === 5)
            {
                $tipDes = [
                    'tip' => '等待用户追问',
                    'time' => 0,
                    'status' => 0,
                    'tip1' => '',
                    'type' => 1
                ];
            } elseif ($questionInfo['status'] === 6)
            {
                $tipDes = [
                    'tip' => '任务已完成',
                    'time' => 0,
                    'status' => 0,
                    'tip1' => '',
                    'type' => 1
                ];
            }

            if ($questionInfo['answer_content'])
            {
                $answerData = [
                    'nickname' => $this->astrInfo['nickname'],
                    'avatar' => $this->astrInfo['avatar'],
                    'create_time' => Util::timeToStr($questionInfo['reply_time']),  // 回复时间
                    'content' => $questionInfo['answer_content'],
                    'duration' => $questionInfo['answer_duration']
                ];
            }
            $addQuestionModel = new Zlcr2UserAddQuestion();
            $addQuestionList = $addQuestionModel->getQuestionAddQuestionInfo($qid);

            $addQuestionData = [];
            $addQuestionSatatus = [
                2 => 1,
                4 => 1,
                5 => 2,
                6 => 3,
            ];
            foreach ($addQuestionList as $addQuestionItem)
            {
                $addQuestionAnswerData = null;
                if ($addQuestionItem['reply_type'] === 1 && $addQuestionItem['status'] === 4)
                {
                    $addQuestionAnswerData = [
                        'nickname' => $this->astrInfo['nickname'],
                        'avatar' => $this->astrInfo['avatar'],
                        'create_time' => Util::timeToStr($addQuestionItem['reply_time']),  // 回复时间
                        'content' => $addQuestionItem['answer_content'],
                        'duration' => $addQuestionItem['answer_duration']
                    ];
                }

                $addQuestionData[] = [
                    'id' => $addQuestionItem['id'],
                    'nickname' => $userNickname,
                    'avatar' => $userAvatar,
                    'create_time' => Util::timeToStr($addQuestionItem['pay_time']),
                    'question' => $addQuestionItem['question'],
                    'status' => $addQuestionSatatus[$addQuestionItem['status']],
                    'status_des' => $addQuestionSatatus[$addQuestionItem['status']] === 2 ? '该追问已取消' : '',
                    'answer_data' => $addQuestionAnswerData
                ];

                if ($addQuestionItem['status'] === 2)
                {   // 待解答
                    $endTime = Util::getToAnswerTime($addQuestionItem['pay_time']);
                    if ($endTime < 0)
                    {   // 超时
                        $tipDes = [
                            'tip' => '追问回复已超时：',
                            'time' => $endTime * -1,
                            'status' => 2,
                            'tip1' => '',
                            'type' => 1
                        ];
                    } else
                    {   // 未超时
                        $tipDes = [
                            'tip' => '追问回复时间还剩：',
                            'time' => $endTime,
                            'status' => 1,
                            'tip1' => $addQuestionItem['order_num'] ? '追问回复超时，已取消' : '追问回复已超时',
                            'type' => $addQuestionItem['order_num'] ? 1 : 2
                        ];
                    }
                }

                if ($addQuestionItem['status'] === 6 || $addQuestionItem['reply_type'] === 2)
                {   // 后台介入
                    $hintDes2 = '追问回复超时，任务收益已扣除。';
                    $tipDes = [
                        'tip' => '追问回复已超时',
                        'time' => 0,
                        'status' => 0,
                        'tip1' => '',
                        'type' => 1
                    ];
                    continue;
                }
            }
            $addQuestionEarning = $taskInfo ? $questionModel->getAddquestionEarning($questionInfo['gid'], $taskInfo['qa_level'], $taskInfo['create_time']) : $questionModel->getAddquestionEarning($questionInfo['gid'], 1, 0);
            $addQuestion = [
                'hint' => '用户收到回复后48小时内可追问，预估每条' . $addQuestionEarning . '元',    //
                'list' => $addQuestionData
            ];

            if ($taskInfo && $taskInfo['status'] === 4)
            {
                $hintDes2 = '回答被用户申诉，平台已判定回答违规，如有疑问请联系官方';
                $tipDes = [
                    'tip' => '任务已结束',
                    'time' => 0,
                    'status' => 0,
                    'tip1' => '',
                    'type' => 1
                ];
            }

            if ($taskInfo && $taskInfo['status'] === 2 && $taskInfo['lock_earning'] === 1)
            {
                $hintDes2 = '本任务收益已扣除，如有疑问请联系官方';
                $tipDes = [
                    'tip' => '任务已结束',
                    'time' => 0,
                    'status' => 0,
                    'tip1' => '',
                    'type' => 1
                ];
            }
        }

        $resData = [
            'nickname' => $userNickname,
            'avatar' => $userAvatar,
            'create_time' => Util::timeToStr($questionInfo['consult_time']),  // 咨询时间
            'user_des' => $userDes,
            'question' => $questionInfo['question'],
            'question_des' => $questionInfo['question_des'],
            'question_type' => $questionInfo['question_type'],
            'status' => $questionInfo['status'],
            'question_data' => $questionData,
            'tip_des' => $tipDes,
            'answer_data' => $answerData,
            'add_question' => $addQuestion,
            'answer_rule' => $answerRule,
            'photo_list' => $questionInfo['question_imgs'],
            'hint_des' => $hintDes ?? '',
            'hint_bottom_buy_bar' => $hintBottomBuyBar ?? '',
            'give_up_data' => $giveUpData,
            'hint_des2' => $hintDes2 ?? '',
            'qid' => $qid
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 解答问题
     */
    public function toAnswer()
    {
        $taskId = input('task_id/d', '');
        $type = input('type/d', 0); //回答类型【1=>语音,2=>文字】
        $content = trim(input('content/s', ''));    //答案内容【语音回答为视频地址】
        $duration = input('duration/d', 0);

        //阿里检测
        if ($type === 2)
        {
            $res = AliyunFilterWord::checkText($content, 'question_astro');
            if ($res)
            {
                return show(config('code.error'), '当前回复中有违规词汇请重新核实');
            }
        }
//        else
//        {
//            $ossHost = Env::get('host.photo');
//            $taskInfo = AliyunFilterWord::submitUrlSound($ossHost . $content, 'question_astro');
//            if ($taskInfo['status'] === true)
//            {
//                $res = AliyunFilterWord::checkSound($taskInfo['task_id']);
//                if ($res['status'] === false)
//                {
//                    return show(config('code.error'), $res['text']);
//                }
//            }
//        }


        $astrTaskModel = new Zlcr2AstrTasks();

        $taskInfo = $astrTaskModel->getInfoById($taskId);
        if (!$taskInfo || $taskInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }

        if ($taskInfo['status'] !== 1)
        {
            return show(config('code.error'), '任务状态异常，请稍后再试～');
        }

        $qid = $taskInfo['qid'];

        $questionModel = new Zlcr2UserQuestion();
        $questionInfo = $questionModel->getInfoById($qid, []);
        if ($questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }

        if (!in_array($questionInfo['status'], [4, 8], true))
        {
            return show(config('code.error'), '问题状态异常，请稍后再试～');
        }

        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '答案类型异常，请稍后再试～');
        }

        if (empty($content))
        {
            return show(config('code.error'), '答案不能为空');
        }

        if ($questionInfo['status'] === 4)
        {   // 回复问题
            $answerRule = $questionModel->answerRule($questionInfo['question_type']);
        } else
        {   // 回复追问
            $answerRule = [
                'text_min' => 30,
                'text_max' => 150,
                'duration_min' => 20,
                'duration_max' => 300,
            ];
        }
        if ($type === 1)
        {
            if ($duration < $answerRule['duration_min'])
            {
                return show(config('code.error'), '语音至少录制' . $answerRule['duration_min'] . '秒');
            }
            if ($duration > $answerRule['duration_max'])
            {
                return show(config('code.error'), '语音最多录制' . $answerRule['duration_max'] . '秒');
            }
        } else
        {
            if (mb_strlen($content) < $answerRule['text_min'])
            {
                return show(config('code.error'), '答案至少' . $answerRule['text_min'] . '字');
            }
            if (mb_strlen($content) > $questionModel->answerRule($questionInfo['question_type'])['text_max'])
            {
                return show(config('code.error'), '答案最多' . $answerRule['text_max'] . '字');
            }
        }

        try
        {
            if ($questionInfo['status'] === 4)
            {   // 回复问题
                $questionModel->UpdateData($qid, [
                    'status' => 5,
                    'is_read' => 0,
                    'uid' => $questionInfo['uid'],
                    'answer_content' => $content,
                    'answer_duration' => $type === 1 ? $duration : 0,
                    'reply_time' => $this->request->time()
                ]);
                // 删除当前进行中任务
                Cache::rm('question_answer:is_underway:' . $this->astrInfo['id']); // 删除 占星师当前有进行中的任务
                // 发送短信通知
                $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
                if ($userInfo && $userInfo['tel'])
                {
                    Util::sendHySms([$userInfo['tel']], '', 52341, ['order_num' => $questionInfo['order_num']]);
                }
                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $questionInfo['uid'],
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 4,//
                    'title' => '问答回复通知',
                    'content' => '你开启的悬赏问答，订单编号：' . $questionInfo['order_num'] . '咨询师已回复，请注意查看，你可以在48小时内追问占星师。',// 消息中心跳转地址
                    'link' => "question_detail?qid={$qid}&need_auth=0",
                    'target' => 'local',
                    'create_time' => $this->request->time()
                ];
                (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
                $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "question_detail?qid={$qid}&need_auth=0"];
                // PUSH推送报告首页
                (new Push())->pushUserMsg($questionInfo['uid'], '你开启的悬赏问答，订单编号：' . $questionInfo['order_num'] . '咨询师已回复，请注意查看，你可以在48小时内追问占星师。', $pushData);

                // 添加问题完成 队列
                // 发送 问答完成检测 队列 48小时后回答
                Util::queuePush('question_answer_question_success_check', ['task_id' => $taskId], 172800);
                // 追问通知检测 40小时后还未追问
                Util::queuePush('question_answer_user_add_question_notify', ['qid' => $qid], 144000);
            } else
            {   // 回复追问
                $addQuestionModel = new Zlcr2UserAddQuestion();
                $addQuestionInfo = $addQuestionModel->getAddQuestionByNotAnswer($qid);
                if (!$addQuestionInfo)
                {
                    return show(config('code.error'), '服务异常，没有待解答的追问～');
                }
                // 追问回复
                $addQuestionModel->UpdateData($qid, $addQuestionInfo['id'], [
                    'status' => 4,
                    'answer_content' => $content,
                    'answer_duration' => $type === 1 ? $duration : 0,
                    'reply_time' => $this->request->time(),
                    'reply_type' => 1,
                    'reply_uid' => $this->astrInfo['id']
                ]);

                // 更新问题状态至待追问
                $questionModel->UpdateData($qid, [
                    'status' => 5,
                    'is_read' => 0,
                    'uid' => $questionInfo['uid'],
                ]);
                // 给追问用户提示有新回复
                (new Zlcr2QuestionUserView())->questionNewAnswer($qid);

                if ($questionInfo['reply_time'] + 172800 < $this->request->time())
                {   // 不在追问时间范围内    172800=60*60*24*2 48小时
                    Util::queuePush('question_answer_question_success_check', ['task_id' => $taskId], 5);
                }

                // 发送短信通知
                $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
                if ($userInfo && $userInfo['tel'])
                {
                    Util::sendHySms([$userInfo['tel']], '', 52349, ['order_num' => $questionInfo['order_num']]);
                }
                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $questionInfo['uid'],
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 4,//
                    'title' => '问答追问回复通知',
                    'content' => '你开启的悬赏问答追问，订单编号：' . $questionInfo['order_num'] . '咨询师已回复，请注意查看。',// 消息中心跳转地址
                    'link' => "question_detail?qid={$qid}&need_auth=0",
                    'target' => 'local',
                    'create_time' => $this->request->time()
                ];
                (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
                $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "question_detail?qid={$qid}&need_auth=0"];
                // PUSH推送报告首页
                (new Push())->pushUserMsg($questionInfo['uid'], '你开启的悬赏问答追问，订单编号：' . $questionInfo['order_num'] . '咨询师已回复，请注意查看。', $pushData);
            }
        }
        catch (\Exception $e)
        {
            Log::write(($questionInfo['status'] === 4 ? '问答' : '问答追问') . '回复异常：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error');
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        return show(config('code.success'), '回复成功');
    }

    /**
     * 常见问题
     */
    public function getFaq()
    {
        $data = [
            [
                'title' => '1.怎么获得问答的接单资格？',
                'content' => "问答有4种类型的考试，3合1考试，考试通过后可获得所有类型问答的接单资格；占星咨询师考试，考试通过后会获得星盘问答的接单资格；塔罗咨询师考试，考试通过后会获得塔罗问答的接单资格；骰子咨询师考试，考试通过后会获得骰子问答的接单资格。\r\n定制报告的考试通过后，便可获得星盘问答的接单资格。",
            ],
            [
                'title' => '2.回答问题和追问需要注意哪些问题？',
                'content' => "一个悬赏问题仅支持问一个问题，如果用户问题中包含多个问题，咨询师有权只回答一个问题。如咨询师发现问题不合理时，可在接单后的5分钟内选择弃答问题。\r\n用户的追问需围绕主问题和咨询师的问题回复进行提问，如果用户的追问不在该范围内或者追问不合理，咨询师有权取消该追问。（取消追问需要取消操作，切不可对用户追问置之不理）",
            ],
            [
                'title' => '3.怎么获得更高的收益？',
                'content' => '能力分越高意味着咨询师的等级越高，越高等级的咨询师的分成比例越高。在接单任务进行过程中，严格按照规范完成任务非常关键，直接影响到你的能力分，间接影响到你的收益。',
            ],
            [
                'title' => '4.哪些行为会扣除能力分？',
                'content' => '任务问题超时回复、追问超时回复、评价星级过低，都会导致扣除能力分。',
            ],
            [
                'title' => '5.哪些行为会增加能力分？',
                'content' => '完成接单任务、获得好评、每日完成5单以上，都可以增加能力分。',
            ],
            [
                'title' => '6.哪些行为会冻结收益？',
                'content' => "当用户对你的回答发起申诉，平台核实申诉成立后，会冻结接单任务的收益；\r\n当追问超时未回复，官方介入后，会冻结接单任务的收益。",
            ],
            [
                'title' => '7.哪些行为会封禁账号？',
                'content' => "当能力分低于80分时，将自动封禁账号；\r\n当30天超过3次回复超时的情况将封禁账号；\r\n当用户申诉问题回复，平台核实申诉成立的情况下，如情节严重可能会封禁账号；\r\n当平台抽查发现存在严重违规的情况下，会封禁账号。",
            ],
        ];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取取消追问任务标签
     * @return Json
     * @throws \Exception
     */
    public function getCannelTaskTag()
    {
        $tagModel = new ZlcrTag();
        $tag = $tagModel->getLevelTag(6, 0);
        $resDatra = [];
        foreach ($tag as $tagItem)
        {
            $resDatra[] = [
                'tid' => (int)$tagItem['id'],
                'name' => $tagItem['tag_name']
            ];
        }

        return show(config('code.success'), '请求成功', $resDatra);
    }

    /**
     * 取消追问任务
     */
    public function cannelAddQuestion()
    {
        $id = input('id/d', 0);
        $tid = input('tid/d', 0);
        $reason = trim(input('reason/s', 0));

        if (!$tid)
        {
            return show(config('code.error'), '请选择取消原因');
        }

        if (empty($reason))
        {
            return show(config('code.error'), '原因描述不能为空');
        }

        if (mb_strlen($reason) > 120)
        {
            return show(config('code.error'), '原因描述最多120字');
        }

        $addQuestionModel = new Zlcr2UserAddQuestion();
        $questionModel = new Zlcr2UserQuestion();
        $addQuestionInfo = $addQuestionModel->getInfoById($id);
        if (!$addQuestionInfo)
        {
            return show(config('code.error'), '服务异常，追问不存在');
        }

        if ($addQuestionInfo['status'] !== 2)
        {
            return show(config('code.error'), '追问状态异常，取消失败');
        }

        $questionInfo = $questionModel->getInfoById($addQuestionInfo['qid'], ['astr_id', 'uid', 'reply_time']);
        if ($questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常，追问不存在');
        }

        $tagInfo = (new ZlcrTag())->getInfoById($tid);
        if (!$tagInfo)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        if ($addQuestionInfo['order_num'])
        {   // 付费追问
            $OrderModel = new \app\common\cachemodel\Orders();
            $orders = $OrderModel->getInfoById($addQuestionInfo['order_num']);
            $res = $OrderModel->refund($questionInfo['uid'], $orders, $orders['total_amount']);
            if ($res['status'])
            {
                $addQuestionModel->UpdateData($addQuestionInfo['qid'], $id, [
                    'status' => 5,
                    'cannel_tag_name' => $tagInfo['tag_name'],
                    'cannel_cause' => $reason
                ]);
                // 问题更新至 已回答 等待追问
                $questionModel->UpdateData($addQuestionInfo['qid'], ['status' => 5,]);
                if ($questionInfo['reply_time'] + 172800 < $this->request->time()) //如果到完成的时候 直接完成 并结算
                {   // 不在追问时间范围内    172800=60*60*24*2 48小时
                    $taskId = (new Zlcr2AstrTasks())->where(['astr_id' => $questionInfo['astr_id'], 'qid' => $addQuestionInfo['qid']])->value('id');
                    if ($taskId)
                    {
                        Util::queuePush('question_answer_question_success_check', ['task_id' => (int)$taskId], 5);
                    }
                }
                // 发送消息
                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $questionInfo['uid'],
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 4,//
                    'title' => '问答追问取消通知',
                    'content' => '你的追问订单：' . $addQuestionInfo['order_num'] . '，因问题违规被取消，资金将原路返还。',// 消息中心跳转地址
                    'link' => "question_detail?qid={$addQuestionInfo['qid']}&need_auth=0",
                    'target' => 'local',
                    'create_time' => $this->request->time()
                ];
                (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
                $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "question_detail?qid={$addQuestionInfo['qid']}&need_auth=0"];
                // PUSH推送报告首页
                (new Push())->pushUserMsg($questionInfo['uid'], '你的追问订单：' . $addQuestionInfo['order_num'] . '，因问题违规被取消，资金将原路返还。', $pushData);
                // 发送短信通知
                $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
                if ($userInfo && $userInfo['tel'])
                {
                    Util::sendHySms([$userInfo['tel']], '', 52346, ['order_num' => $addQuestionInfo['order_num']]);
                }
                return show(config('code.success'), '取消成功');
            } else
            {
                Log::write('问答追问【' . $id . '】退款失败', 'error', true);
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
        } else
        {   // 免费追问
            $addQuestionModel->UpdateData($addQuestionInfo['qid'], $id, [
                'status' => 5,
                'cannel_tag_name' => $tagInfo['tag_name'],
                'cannel_cause' => $reason
            ]);
            // 问题更新至 已回答 等待追问
            $questionModel->UpdateData($addQuestionInfo['qid'], ['status' => 5,]);
            if ($questionInfo['reply_time'] + 172800 < $this->request->time()) //如果到完成的时候 直接完成 并结算
            {   // 不在追问时间范围内    172800=60*60*24*2 48小时
                $taskId = (new Zlcr2AstrTasks())->where(['astr_id' => $questionInfo['astr_id'], 'qid' => $addQuestionInfo['qid']])->value('id');
                if ($taskId)
                {
                    Util::queuePush('question_answer_question_success_check', ['task_id' => (int)$taskId], 5);
                }
            }
            // 发送消息
            $messageData = [
                'status' => 0,
                'is_read' => 0,
                'range' => $questionInfo['uid'],
                'type' => 2,
                'reid' => 0,
                'cid' => 4,//
                'title' => '问答追问取消通知',
                'content' => '你开启的悬赏问答追问，因问题违规被取消，请重新追问',// 消息中心跳转地址
                'link' => "question_detail?qid={$addQuestionInfo['qid']}&need_auth=0",
                'target' => 'local',
                'create_time' => $this->request->time()
            ];
            (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
            $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "question_detail?qid={$addQuestionInfo['qid']}&need_auth=0"];
            // PUSH推送报告首页
            (new Push())->pushUserMsg($questionInfo['uid'], '你开启的悬赏问答追问，因问题违规被取消，请重新追问', $pushData);
            // 发送短信通知
            $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
            if ($userInfo && $userInfo['tel'])
            {
                Util::sendHySms([$userInfo['tel']], '', 52347, []);
            }
            return show(config('code.success'), '取消成功');
        }
    }

    /**
     * 问答历史任务
     */
    public function getAstrTaskRecordList()
    {
        $questionType = input('question_type/d', 0);

        $map = ['t.astr_id' => $this->astrInfo['id'], 't.status' => ['in', [2, 3, 4, 5, 6, 7]]];
        if ($questionType)
        {
            $map['t.question_type'] = $questionType;
        }
        $astrModel = new ZlcrAstr();
        $zlcr2UserQuestionComment = new Zlcr2UserQuestionComment();
        $addQuestionModel = new Zlcr2UserAddQuestion();

        $data = Db::table('wechat_backup_07_18_14_43_00.zlcr2_astr_tasks')->alias('t')
            ->join('wechat_backup_07_18_14_43_00.zlcr2_user_question q', 't.qid=q.id')
            ->field('t.id task_id,q.id qid,q.question_type,q.uid,q.is_synastry is_merge,t.create_time astr_receiving_time,q.is_anonymity,q.question,q.status,q.is_comment,q.success_time,t.earning,t.qa_level,t.status tstatus,t.deduct_earning_time,t.update_time,t.lock_earning')
            ->where($map)
            ->order('t.id desc')
            ->paginate()
            ->toArray();

        $resData = [];
        $statusDes = [  //状态 1=>进行中 2=>已完成 3=>已弃答 4=>用户申述已取消 5=>答案回复超时 6追问回复超时未完成 7=>抽查被扣除收益
            2 => '已完成',
            3 => '已弃答',
            4 => '扣除收益',
            5 => '已取消：回复超时',
            6 => '扣除收益：追问回复超时',
            7 => '扣除收益',
        ];
        $userInfoList = [];
        foreach ($data['data'] as $datum)
        {
            $datum['tstatus'] = $datum['tstatus'] === 7 ? 4 : $datum['tstatus'];
            $tagName = '';
            if ($datum['is_comment'])
            {
                $commentInfo = $zlcr2UserQuestionComment->getInfoById($datum['qid'], ['tag_name', 'level', 'comment']);
                $tagName = $commentInfo['tag_name'];
            }
            $addQuestionNum = $addQuestionModel->getQuestionAddQuestionNum($datum['qid']);
            $proportion = ($astrModel->getAstrQuestionAnswerProportion((int)$datum['astr_receiving_time'], (int)$datum['question_type'], (int)$datum['qa_level']) * 100) . '%';

            $nickname = '匿名用户';
            $avatar = '/test/question_answer/anonymity1.png';
            if ($datum['is_anonymity'] !== 1)
            {
                if (isset($userInfoList[$datum['uid']]))
                {
                    $nickname = $userInfoList[$datum['uid']]['nickname'];
                    $avatar = $userInfoList[$datum['uid']]['avatar'];
                } else
                {
                    $userInfo = (new User())->getUserinfo(['id' => $datum['uid']]);
                    $nickname = $userInfo['nickname'];
                    $avatar = $userInfo['avatar'];
                    $userInfoList[$datum['uid']] = [
                        'nickname' => $nickname,
                        'avatar' => $avatar,
                    ];
                }
            }

            $desList = [
                [
                    'title' => '任务编号:',
                    'des' => $datum['qid'],
                    'type' => 0
                ]
            ];
            $status = (int)$datum['tstatus'];
            if ($status === 2 && (int)$datum['lock_earning'] === 1)
            {
                $status = 7;
            }
            if ($status === 5)
            {
                $desList[] = [
                    'title' => '取消时间:',
                    'des' => date('Y-m-d H:i:s', $datum['update_time']),
                    'type' => 1
                ];
            } elseif ($status === 3)
            {
                $desList[] = [
                    'title' => '弃答时间:',
                    'des' => date('Y-m-d H:i:s', $datum['update_time']),
                    'type' => 1
                ];
            } else
            {
                $desList[] = [
                    'title' => '税前收益:',
                    'des' => $datum['earning'],
                    'type' => 1
                ];
                $desList[] = [
                    'title' => '分成比例:',
                    'des' => $proportion,
                    'type' => 1
                ];
                $desList[] = [
                    'title' => '追问次数:',
                    'des' => $addQuestionNum . '次',
                    'type' => 1
                ];
                if ($status === 2)
                {   // 已完成   评价信息
                    $desList[] = [
                        'title' => '评价状态:',
                        'des' => $datum['is_comment'] ? (string)$commentInfo['level'] ?? '3' : '未评价',
                        'type' => $datum['is_comment'] ? 2 : 1
                    ];
                }
                $desList[] = [
                    'title' => '完成时间:',
                    'des' => $status === 6 ? date('Y-m-d H:i:s', $datum['deduct_earning_time']) : date('Y-m-d H:i:s', $datum['success_time']),
                    'type' => 1
                ];
                if (in_array($status, [6, 7], true))
                {
                    $desList[] = [
                        'title' => '扣除时间:',
                        'des' => date('Y-m-d H:i:s', $datum['deduct_earning_time']),
                        'type' => 1
                    ];
                }
            }

            $successTime = in_array($status, [3, 5, 7], true) ? date('Y-m-d H:i:s', $datum['update_time']) : date('Y-m-d H:i:s', $datum['success_time']);

            $resData[] = [
                'task_id' => $datum['task_id'],
                'qid' => $datum['qid'],
                'question_type' => (int)$datum['question_type'],
                'question' => $datum['question'],
                'nickname' => $nickname,
                'avatar' => $avatar,
                'is_merge' => $datum['is_merge'],
                'astr_receiving_time' => date('Y-m-d H:i:s', $datum['astr_receiving_time']),
                'success_time' => $status === 6 ? date('Y-m-d H:i:s', $datum['deduct_earning_time']) : $successTime,
                'add_question_num' => $addQuestionNum,
                'is_comment' => $datum['is_comment'],
                'comment_level' => $commentInfo['level'] ?? 0,
                'comment_tag_name' => $tagName,
                'comment' => $commentInfo['comment'] ?? '',
                'earnings' => $datum['earning'],
                'proportion' => $proportion,
                'status' => $status,
                'status_des' => $statusDes[$datum['tstatus']],
                'des_list' => $desList,
            ];
        }
        $data['data'] = $resData;

        return show(config('code.success'), '请求成功', $data);
    }
}
